<?php
namespace frontend\modules\Api\controllers;

use common\models\StockRecord;
use common\models\TallyCategory;
use common\models\TallyRecord;
use common\services\TallyArapService;
use common\services\TallyPmService;
use common\services\TallyRecordService;
use common\services\TallyStockRecordService;
use common\services\ToolService;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\base\DynamicModel;
use common\services\TallyStockProductService;

/**
 * Class StockRecordController
 *
 * @package frontend\modules\Api\controllers
 * @desc 库存 增加销售采购记录（涉及到账单）
 */
class StockRecordController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    /**
     * 记录列表
     * @throws
     */
    public function actionLists()
    {
        $condition = Yii::$app->request->get(); // keywords 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockRecordService::getList($tallyId,$condition);

        // 产品明细格式化
        if(!empty($list['data'])) {
            foreach ($list['data'] as $lk =>  $lv) {
                $list['data'][$lk]['product_detail'] = json_decode($lv['product_detail'],true);
                $list['data'][$lk]['sales_type_str'] = StockRecord::getOptStr($lv['sales_type']);
                $list['data'][$lk]['state_txt'] = StockRecord::getStateStr($lv['state']);
            }
        }

        return self::successResponse($list);
    }

    /**
     * 增加库存账单记录
     * @throws
     */
    public function actionAdd()
    {
        $form = DynamicModel::validateData([
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'uid'   => $this->_user['id'],
            'record_id' => 0,
            'house_id' => Yii::$app->getRequest()->post('house_id',''),
            'house_title' => Yii::$app->getRequest()->post('house_title',''),
            'category_id' => Yii::$app->getRequest()->post('category_id',''),
            'category_name' => Yii::$app->getRequest()->post('category_name',''),
            'account_id' => Yii::$app->getRequest()->post('account_id',''),
            'account_name' => Yii::$app->getRequest()->post('account_name',''),
            'project_id'   => Yii::$app->getRequest()->post('project_id',0),// 项目
            'store_id'     => Yii::$app->getRequest()->post('store_id',0), // 商家
            'product_detail'  =>Yii::$app->getRequest()->post('product_detail',[]),
            'tally_date'  => Yii::$app->getRequest()->post('tally_date',''),
            'tally_time'  => '',
            'sales_type'  => Yii::$app->getRequest()->post('sales_type',10),
            'is_gua'  => Yii::$app->getRequest()->post('is_gua',0),
            'state' => 0,
            'memo'  => Yii::$app->getRequest()->post('memo',''),
            'total_num' => 0,
            'total_money' => 0,
            'tally_money' => 0,
            'stock_id' => 0,
            'future_id'=>0,
            'amount' => 0,
            'type' => 10,
            'record_type' => 0,
            'arap_id' => 0,
        ],[
            [['tally_id','category_id','house_id','product_detail'], 'required'],
            ['memo', 'filter', 'filter' => 'trim'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        if(empty($form->product_detail)) {
            return self::failureResponse(500,'产品明细不能为空');
        }
        if(!$form->product_detail[0]['product_id']) {
            return self::failureResponse(500,'请补全产品明细');
        }
        // 挂账操作 必须选择客户或者供应商
        $isArap = false;
        if(in_array( $form->category_id, TallyCategory::$gzIds) || $form->is_gua == 1 || $form->is_gua == true ) {
            if(!$form->store_id) {
                return self::failureResponse(500,'挂账操作必须选择客户或者供应商！');
            }
            $isArap = true;
        }

        // 填充默认的账单日期为今天
        if(!$form->tally_date) {
            $form->tally_date = date('Y-m-d');
            $form->tally_time = date('Y-m-d H:i:s');
        }else {
            // date + 00:00:00
            $form->tally_time = date('Y-m-d H:i:s',strtotime($form->tally_date));
        }

        // 账单收支类型
        $form->record_type = StockRecord::getRecordInOutVal($form->sales_type);
        // 金额统计
        $totalMoney = 0;
        $totalNum = 0;
        foreach ($form->product_detail as $fv) {
            if($fv['product_id']) {
                $totalMoney = ToolService::groupMathAdd([
                    $totalMoney,
                    $fv['money']
                ]);
                $totalNum = ToolService::groupMathAdd([
                    $totalNum,
                    $fv['num']
                ]);
            }
        }

        $form->total_num = $totalNum;
        $form->total_money = $totalMoney;
        $form->tally_money = $totalMoney;
        // 检查用户操作权限
        $this->checkRolePermission($this->_user['id'],$form->tally_id,'read');
        $userRole = TallyPmService::getRole($form->uid,$form->tally_id) ;
        // 开启事务 计入账本
        $connection = Yii::$app->db->beginTransaction();
        try{
            if($isArap) {
                $arapForm = $form;
                $arapForm->state = TallyRecord::getDefaultStateByRole($userRole,$form->tally_id);
                $arapForm->amount = $totalMoney;
                $arapForm->type = StockRecord::getRecordInOutVal($form->sales_type);
                $arapId = TallyArapService::create(ArrayHelper::toArray($arapForm));
                if(!$arapId) {
                    throw new \Exception(TallyArapService::getError());
                }
                $form->arap_id = $arapId;
            }

            // 创建库存记录 拿到库存记录ID
            $stockId = TallyStockRecordService::create(ArrayHelper::toArray($form));
            if(!$stockId){
                throw new \Exception(TallyStockRecordService::getError());
            }

            // 区分挂账
            if(!$isArap) {
                // 标记库存ID
                $recordArrForm = $form;
                $recordArrForm->stock_id = $stockId;
                // 获取默认记账状态
                $recordArrForm->state = TallyRecord::getDefaultStateByRole($userRole,$form->tally_id);
                $recordArrForm->amount = $totalMoney;
                $recordArrForm->type = StockRecord::getRecordInOutVal($form->sales_type);
                // 创建账单记录
                $tallyRecordId = TallyRecordService::create(ArrayHelper::toArray($recordArrForm
                ));
                if(!$tallyRecordId){
                    throw new \Exception(TallyRecordService::getError());
                }

                // 这里对状态进行拦截 只有状态正常的才要进入账户金额统计
                if( $recordArrForm->state == TallyRecord::STATE_VALID){
                    TallyRecordService::calRelationAmount($recordArrForm);
                    // 这里更新原有状态 以及操作遍历商品进行出入库管理
                    TallyStockRecordService::handleProductFlow($stockId,$tallyRecordId);
                }
            }

            $connection->commit();
            // 触发账单记录事件
//            $this->triggerEvents([
//                'tally_id' => $form->tally_id,
//                'uid'   => $form->uid,
//                'type'  => 2,
//                'content' => '添加账单,id:'.$result.',金额:'.$form->amount,
//            ]);
            return self::successResponse(['id'=>$stockId]);
        }catch (\Exception $ex){
            $connection->rollBack();
            return self::failureResponse(500,'新增失败.'.$ex->getMessage());
        }
    }

    /**
     * 删除库存记录（暂时用不到）
     * @throws
     */
    public function actionDel()
    {
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'记录Id不能为空');
        }
        $tallyId = Yii::$app->getRequest()->post('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本ID不能为空');
        }

        // 检查对账本的操作权限
        $this->checkRolePermission($this->_user['id'],$tallyId,'write');

        $result = TallyStockRecordService::delete([
            'id'    => $id,
            'tally_id' => $tallyId,
            'uid' => $this->_user['id'],
        ]);

        if($result){
            return self::successResponse();
        }else{
            return self::failureResponse(500,'删除失败.'.TallyStockRecordService::getError());
        }
    }

    /**
     * 库存记录数据导出
     * @throws \yii\base\ExitException
     */
    public function actionExport()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        // 默认取出所有状态 修改返回为data的bug
        $list = TallyStockRecordService::getExportAll($condition);
        // 遍历拼装附件数据
        $retData = [] ;
        foreach ($list as $lv) {
            $tmpData = [
                $lv['house_title'],
                $lv['category_title'],
                $lv['total_money'],
                $lv['tally_date'],
                $lv['account_name'],
                StockRecord::getOptStr($lv['sales_type']),
                $lv['memo'],
                $lv['created_time'], //录入时间
            ];
            $retData[] = $tmpData;
        }
//        print_r($list);die;
        $filename = '库存账单_'.$this->_user['id'].'_'.date('YmdHis').'csv';
        ToolService::downLoadCsv($filename,[
            '仓库',
            '账单类别',
            '账单金额',
            '账单日期',
            '结算账户',
            '操作类型',
            '备注',
            '录入时间',
        ],$retData);
        $filepath = Yii::$app->request->hostInfo.'/index/down-export?file='.$filename;
        return self::successResponse(['filepath'=>$filepath]);
    }
}
